﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace TestWpf
{
    /// <summary>
    /// GetLocationForm.xaml 的交互逻辑
    /// </summary>
    public partial class GetLocationForm : Window
    {
        public GetLocationForm()
        {
            InitializeComponent();
        }

        private MouseHook mh;
        private Point mousepoint;
        private Version currentVersion;
        private Version compareToVersion;
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            mh = new MouseHook();
            mh.SetHook();
            mh.getLocationEvent += new MouseHook.GetLocationEvent((s) =>
            {
                mousepoint = s;
            });
            mh.MouseClickEvent += mh_MouseClickEvent;
            currentVersion = Environment.OSVersion.Version;
            compareToVersion = new Version("6.2");
        }

        private void mh_MouseClickEvent(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Window window = System.Windows.Window.GetWindow(this.btn);
                Point point = this.btn.TransformToAncestor(window).Transform(new Point(0, 0));

                double mousepointX;
                double mousepointY;
                if (currentVersion.CompareTo(compareToVersion) >= 0)
                {
                    mousepointX = this.mousepoint.X / 2;
                    mousepointY = this.mousepoint.Y / 2;
                }
                else
                {
                    mousepointX = this.mousepoint.X;
                    mousepointY = this.mousepoint.Y;
                }

                Console.WriteLine(string.Format(
                    "==========================\n"+
                    "控件左上角位置：{0}，{1}\n" +
                    "控件右下角位置：{2}，{3}\n" +
                    "鼠标点击位置：{4}，{5}", 
                    point.X,point.Y,
                    point.X + this.btn.Width,point.Y + this.btn.Height,
                    mousepointX, mousepointY
                    ));

                if ((mousepointX > point.X + this.btn.Width)
                    || (mousepointX < point.X)
                    || (mousepointY > point.Y + this.btn.Height
                        || (mousepointY < point.Y)))
                {
                    //TODO:位于鼠标点击控件外区域执行的代码
                    //
                }
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        private void Window_Closed(object sender, EventArgs e)
        {
            mh.UnHook();
        }


    }
}
